window.addEventListener("load", () => {
	const canvas = document.querySelector("canvas");
	const context = canvas.getContext("2d");
	const computedStyle = window.getComputedStyle(canvas);
	const canvasWidth = parseInt(computedStyle.width.split("px")[0]);
	const canvasHeight = parseInt(computedStyle.height.split("px")[0]);
	// 发送弹幕
	const send = document.querySelector("#send");
	const barrageList = [];
	send.addEventListener("click", () => {
		send.disabled = true;
		send.style.backgroundColor = "#e7e7e7";
		send.style.color = "#a0a0a0";
		send.innerHTML = "5s";
		let countDown = 4;
		let timer = setInterval(() => {
			send.innerHTML = `${countDown}s`;
			countDown--;
			if (countDown <= 0) {
				send.disabled = false;
				send.style.backgroundColor = "#5192fe";
				send.style.color = "#fff";
				send.innerHTML = "发送";
				clearInterval(timer);
				timer == null;
			}
		}, 1000);
		// 获取弹幕内容,添加到弹幕列表中(弹幕对象包括x坐标和内容)
		const barrage = document.querySelector("#barrage").value;
		const loc = [25, 50, 75];
		barrageList.push({
			x: canvasWidth,
			y: loc[Math.floor(Math.random() * 3)],
			text: barrage,
		});
	});

	context.font = "20px 微软雅黑";
	context.fillStyle = "#fff";
	const draw = () => {
		// 耗时代码
		barrageList.forEach((item) => {
			item.x--;
		});
		requestAnimationFrame(() => {
			context.clearRect(0, 0, canvasWidth, canvasHeight);
			barrageList.forEach((item) => {
				context.fillText(item.text, item.x, item.y);
			});
		});
		setTimeout(draw, 1000 / 60);
	};
	draw();
});
